package com.kuang.conreoller;



import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyConreoller {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro");
        return "index";
    }

    @RequestMapping({"/user/add"})
    public String add(Model model){
        return "/user/add";
    }

    @RequestMapping({"/user/update"})
    public String update(Model model){
        return "/user/update";
    }

    @RequestMapping({"/toLogin"})
    public String toLogin(Model model){
        return "login";
    }

    @RequestMapping({"/login"})
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token); // 执行登录操作
            return "index";
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg","用户名错了！");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg","密码错了！");
            return "login";
        }

    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面！";
    }
}
